package org.chench.extra.logsift.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.chench.extra.logsift.bo.FeiShuLog;
import org.chench.extra.logsift.bo.LogApp;
import org.chench.extra.logsift.config.properties.AppProperties;
import org.chench.extra.logsift.service.LogHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.stream.Collectors;

/**
 * 将日志信息发送到飞书
 * @author chench
 * @date 2025.05.23
 */
@Service
public class FeiShuHandlerImpl implements LogHandler {
    private static final Logger logger = LoggerFactory.getLogger(FeiShuHandlerImpl.class);

    // 使用固定大小的队列保存日志消息，用于控制发送飞书消息的频率
    private ArrayBlockingQueue<FeiShuLog> logDataQueue = new ArrayBlockingQueue(1024);
    private AppProperties appProperties;

    @Override
    public void handleLog(String logAppName, Path filePath, Map<String, Object> logData, String line) {
        LogApp logApp = this.appProperties.getLogApp(logAppName);
        if (StrUtil.isEmpty(logApp.getForwardUrl())) {
            logger.warn("handleLog forwardUrl is empty! logAppName:{}, content:{}", logAppName, line);
            return;
        }
        logDataQueue.offer(new FeiShuLog(line, logApp.getForwardUrl()));
    }

    @Autowired
    public void setAppProperties(AppProperties appProperties) {
        this.appProperties = appProperties;
    }

    /**
     * 每1秒执行一次发送
     */
    @Scheduled(fixedRate = 1 * 1000)
    public void send() {
        Map<String, List<String>> map = new HashMap<>();
        int size = 3;
        for (int i = 0; i < size; i++) {
            FeiShuLog log = this.logDataQueue.poll();
            if (log == null) {
                continue;
            }
            List<String> list = map.get(log.getHook());
            if (list == null) {
                list = new ArrayList<>();
                list.add(log.getContent());
                map.put(log.getHook(), list);
            } else {
                list.add(log.getContent());
            }
        }

        if (map.isEmpty()) {
            return;
        }

        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String url = entry.getKey();
            String content = entry.getValue().stream().collect(Collectors.joining("\n"));
            sendTextMessage(url, content);
        }
    }

    private void sendTextMessage(String url, String content) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json; charset=utf-8");

            Map<String, Object> message = new HashMap<>();
            message.put("msg_type", "text");

            Map<String, Object> contentMap = new HashMap<>();
            contentMap.put("text", content);
            message.put("content", contentMap);

            StringEntity entity = new StringEntity(JSONObject.toJSONString(message), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            logger.info("飞书消息发送结果:{}", result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}